package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatProperties weChatProperties;


    private static final String URI="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User  login(UserLoginDTO loginDTO) {
        //userMapper.login(loginDTO);

        //1、Httpclient 验证登录凭证
        Map<String,String> paramMap= new HashMap<>();
         paramMap.put("appid",weChatProperties.getAppid());
         paramMap.put("secret",weChatProperties.getSecret());
         paramMap.put("js_code", loginDTO.getCode());
         paramMap.put("grant_type","authorization_code");

        String res = HttpClientUtil.doGet(URI, paramMap);
        log.info("res："+res);

        //2、解析响应结果，获取openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid =(String) jsonObject.get("openid");
        log.info("openid："+openid);//打印openid
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //3、判断是否是新用户，根据openid查询用户
        User user = userMapper.getUserByOpenid(openid);
        if(user==null){
            user=new User();
            user.setOpenid(openid);
            user.setName(openid.substring(0,8));
            user.setSex("男");
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        return user;
    }
}
